<?php

namespace app\admin\controller\factory;

use app\admin\model\AuthGroupAccess;
use app\common\controller\Backend;
use app\common\library\Auth;
use app\common\model\Admin;
use app\common\model\Area;
use app\common\model\shop\Data;
use app\common\model\User;
use fast\Tree;
use PDOException;
use think\Db;
use think\exception\ValidateException;
use think\Model;
use think\Config;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class Factory extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';
    protected $noNeedRight = ['dashboard'];

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;
    protected $group_id = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
        $this->modelValidate = true;
        $this->group_id = $this->auth->getGroupIds()[0];
        $this->view->assign('group_id', $this->auth->getGroupIds()[0]);
        $this->view->assign("admin_id", $this->auth->id);
        $this->assignconfig('city_lists', Admin::whereIn('id', AuthGroupAccess::where('group_id', 2)->column('uid'))->column('id,nickname'));
        $this->assignconfig('county_lists', Admin::whereIn('id', AuthGroupAccess::where('group_id', 5)->column('uid'))->column('id,nickname'));
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {

                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            if ($this->group_id == 2) {
                $admin = $this->auth->getUserInfo();
                $ids = Area::whereIn('pid', $admin['region_id'])->column('id');

                $admin = new Admin;
                foreach ($ids as $v) {
                    $admin->whereOr("FIND_IN_SET({$v},region_id)");
                }
                $admin_ids = $admin->column('id');
                array_push($admin_ids, $this->auth->id);
                $this->model->whereIn('company_id', $admin_ids);
            }

            if ($this->group_id == 5) {
                $this->model->where('company_id', $this->auth->id);
            }
            $this->model->where('role', 'factory');
            $list = $this->model
                ->with(['category', 'county'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
                $v->rank = ($list->currentPage() - 1) * $list->listRows() + $k + 1;
                $v->order = \app\common\model\FeeOrder::where(['user_id' => $v['id'], 'is_pay' => 1])->find();
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * Selectpage的实现方法
     *
     * 当前方法只是一个比较通用的搜索匹配,请按需重载此方法来编写自己的搜索逻辑,$where按自己的需求写即可
     * 这里示例了所有的参数，所以比较复杂，实现上自己实现只需简单的几行即可
     *
     */
    function selectpage()
    {
        //设置过滤方法
        $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
        if ($istree) {
            $word = [];
            $pagesize = 999999;
        }
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
            $pagesize = 999999;
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                $searchfield = str_replace(',', $logic, $searchfield);
                $word = array_filter(array_unique($word));
                if (count($word) == 1) {
                    $query->where($searchfield, "like", "%" . reset($word) . "%");
                } else {
                    $query->where(function ($query) use ($word, $searchfield) {
                        foreach ($word as $index => $item) {
                            $query->whereOr(function ($query) use ($item, $searchfield) {
                                $query->where($searchfield, "like", "%{$item}%");
                            });
                        }
                    });
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        if ($this->group_id == 2) {
            $admin = $this->auth->getUserInfo();
            $ids = Area::whereIn('pid', $admin['region_id'])->column('id');
            $admin = new Admin;
            foreach ($ids as $v) {
                $admin->whereOr("FIND_IN_SET({$v},region_id)");
            }
            $admin_ids = $admin->column('id');
            array_push($admin_ids, $this->auth->id);
            $this->model->whereIn('company_id', $admin_ids);
        }
        if ($this->group_id == 5) {
            $this->model->where('company_id', $this->auth->id);
        }
        $list = [];
        $total = $this->model->where($where)->count();

        if ($total > 0) {
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }

            $fields = is_array($this->selectpageFields) ? $this->selectpageFields : ($this->selectpageFields && $this->selectpageFields != '*' ? explode(',', $this->selectpageFields) : []);

            //如果有primaryvalue,说明当前是初始化传值,按照选择顺序排序
            if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
                $primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
                //修复自定义data-primary-key为字符串内容时，给排序字段添加上引号
                $primaryvalue = array_map(function ($value) {
                    return '\'' . $value . '\'';
                }, $primaryvalue);

                $primaryvalue = implode(',', $primaryvalue);

                $this->model->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
            } else {
                $this->model->order($order);
            }
            if ($this->group_id == 2) {
                $admin = $this->auth->getUserInfo();
                $ids = Area::whereIn('pid', $admin['region_id'])->column('id');
                $admin = new Admin;
                foreach ($ids as $v) {
                    $admin->whereOr("FIND_IN_SET({$v},region_id)");
                }
                $admin_ids = $admin->column('id');
                array_push($admin_ids, $this->auth->id);
                $this->model->whereIn('company_id', $admin_ids);
            }
            if ($this->group_id == 5) {
                $this->model->where('company_id', $this->auth->id);
            }
            $datalist = $this->model->where($where)
                ->page($page, $pagesize)
                ->select();
            foreach ($datalist as $index => $item) {
                unset($item['password'], $item['salt']);
                if ($this->selectpageFields == '*') {
                    $result = [
                        $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
                        $field      => isset($item[$field]) ? $item[$field] : '',
                    ];
                } else {
                    $result = array_intersect_key(($item instanceof Model ? $item->toArray() : (array)$item), array_flip($fields));
                }
                $result['pid'] = isset($item['pid']) ? $item['pid'] : (isset($item['parent_id']) ? $item['parent_id'] : 0);
                $list[] = $result;
            }
            if ($istree && !$primaryvalue) {
                $tree = Tree::instance();
                $tree->init(collection($list)->toArray(), 'pid');
                $list = $tree->getTreeList($tree->getTreeArray(0), $field);
                if (!$ishtml) {
                    foreach ($list as &$item) {
                        $item = str_replace('&nbsp;', ' ', $item);
                    }
                    unset($item);
                }
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }
    /**
     * 添加
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            $factory_item = Config::get('site.factory_item');
            $fee_items = [];
            foreach ($factory_item as $key => $item) {
                $fee_items[] = [
                    'item'  => $key,
                    'amount'=> ''
                ];
            }

            $this->view->assign('fee_items', json_encode($fee_items));
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        $user = \app\common\model\User::where(['username' => $params['username']])->find();
        if ($user) {
            $this->error('该账号名已存在');
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $this->modelSceneValidate = true;
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.shop' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $params['role'] = 'factory';
            if ($this->group_id == 5) {
                $params['company_id'] = $this->auth->id;
            }

            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException | PDOException | \Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            # - 判断是否json字符串
            $items = json_decode($row->fee_items, true) ?: [];

            $factory_item = Config::get('site.factory_item');
            $fee_items = [];
            foreach ($factory_item as $key => $val) {
                $item = [ 'item' => $key, 'amount' => 0 ];
                foreach ($items as $v) {
                    if ($key == $v['item']) {
                        $item['amount'] = $v['amount'];
                    }
                }
                $fee_items[] = $item;
            }

            $this->view->assign('fee_items', json_encode($fee_items));

            $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $user = \app\common\model\User::where(['username' => $params['username'], 'id' => ['neq', $row->id]])->find();
        if ($user) {
            $this->error('该账号名已存在');
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.shop' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $upflag = 0;
            if ($params['category_id'] != $row->category_id) {
                $upflag = 1;
            }

            $result = $row->allowField(true)->save($params);
            if ($result) {
                if ($params['status'] == 'hidden')
                    User::where('role', 'shop')->where('factory_id', $ids)->where('status', 'normal')->update(['status' => 'hidden']);
                else
                    User::where('role', 'shop')->where('factory_id', $ids)->where('status', 'hidden')->update(['status' => 'normal']);
                if ($upflag) {
                    Data::update(['category_id' => $params['category_id']], ['factory_id' => $row->id], 'category_id');
                }
            }
            Db::commit();
        } catch (ValidateException | PDOException | \Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }

    /**
     * 查看
     */
    public function dashboard()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {

                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            if ($this->group_id == 2) {
                $admin = $this->auth->getUserInfo();
                $ids = Area::whereIn('pid', $admin['region_id'])->column('id');

                $admin = new Admin;
                foreach ($ids as $v) {
                    $admin->whereOr("FIND_IN_SET({$v},region_id)");
                }
                $admin_ids = $admin->column('id');
                array_push($admin_ids, $this->auth->id);
                $this->model->whereIn('company_id', $admin_ids);
            }

            if ($this->group_id == 5) {
                $this->model->where('company_id', $this->auth->id);
            }
            $this->model->where('role', 'factory');
            $list = $this->model
                ->with(['category', 'county'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
                $v->rank = ($list->currentPage() - 1) * $list->listRows() + $k + 1;
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function select()
    {
        $list = $this->model->where('role', 'factory')->order('id ASC')->select();
        $data = [];
        foreach ($list as $v) {
            $data[$v['id']] = $v['nickname'];
        }
        return json($data);
    }
}
